# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.db.models import Q
from django.core import serializers
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.forms.models import modelformset_factory


from mydict.dict.models import Vocabulary, Senses

def index(request):
    return render_to_response('dict/index.html', {'latest_poll_list': []})

def search(request):
    if request.is_ajax():
        q = request.GET.get( 'skey' )
        if q is not None:
            try:
                word = Vocabulary.objects.get(word__exact=q)
            except (Vocabulary.DoesNotExist):
                return HttpResponse('[{"pk": 0}]', mimetype="application/json")
            paginator = Paginator(word.senses_set.all(), 25) # Show 25 contacts per page

            # Make sure page request is an int. If not, deliver first page.
            try:
                page = int(request.GET.get('page', '1'))
            except ValueError:
				page = 1

            # If page request (9999) is out of range, deliver last page of results.
            try:
                words = paginator.page(page)
            except (EmptyPage, InvalidPage):
                words = paginator.page(paginator.num_pages)

            response = HttpResponse(mimetype="application/json")
            json_serializer = serializers.get_serializer("json")()
            json_serializer.serialize(words.object_list, ensure_ascii=False, stream=response)
            return response
    else:
        return HttpResponse("this is not ajax request!!", mimetype="application/javascript")

def edit(request, word_id):

    return render_to_response('dict/edit.html', {'latest_poll_list': []})

def create(request):
    if request.method == 'POST': # If the form has been submitted...
        if request.user.is_authenticated():
            wid = request.POST.get( 'word_id' )
            if wid is not None:
                WordFormSet = modelformset_factory(Vocabulary)
                MeaningFormSet = modelformset_factory(Senses)
                print "word valid"
                # formWord = WordFormSet(request.POST) # A form bound to the POST data
                print "sense valid"
                print request.POST
                formMeaning = MeaningFormSet(request.POST) # A form bound to the POST data
                if (formWord.is_valid() and formMeaning.is_valid()): # All validation rules pass
                    return HttpResponse("success!!", mimetype="application/javascript")
            else:
                word = request.POST.get( 'word' )
                meaning = request.POST.get( 'meaning' )
                print "====================================="
                print request.user
                if word and meaning: # All validation rules pass
                    wordModel = Vocabulary(user=request.user, word=word)
                    wordModel.save()
                    print "user word save"
                    meaningModel = Senses(user=request.user, word=wordModel, meaning=meaning)
                    meaningModel.save()
                    return HttpResponse("success!!", mimetype="application/javascript")
        else:
            return HttpResponse("not logined!!", mimetype="application/javascript")

def show(request, word_id):

    return render_to_response('dict/show.html', {'latest_poll_list': []})

def destroy(request, word_id):

    return render_to_response('dict/index.html', {'latest_poll_list': []})